package controllers

import (
	"net/http"

	"github.com/gin-gonic/gin"

	"go_user_manager/internal/domain/service"
	"go_user_manager/pkg/adapters/agin"
	"go_user_manager/pkg/framework"
)

type AuthController struct {
	logger    framework.Logger
	userSvc   service.IUserService
	staticDir string
}

type LoginRequest struct {
	Username string `json:"user_name" binding:"required"`
	Password string `json:"password" binding:"required"`
}

type LoginResponse struct {
	Token string `json:"token"`
}

func NewAuthController(logger framework.Logger, userSvc service.IUserService) *AuthController {
	return &AuthController{
		logger:    logger,
		userSvc:   userSvc,
		staticDir: "./static",
	}
}

func (c *AuthController) InitRouter(router *gin.Engine) {
	// 静态文件服务
	router.Static("/static", c.staticDir)

	// 前端页面路由
	router.GET("/", func(ctx *gin.Context) {
		ctx.File(c.staticDir + "/index.html")
	})

	router.GET("/dashboard", func(ctx *gin.Context) {
		ctx.File(c.staticDir + "/dashboard.html")
	})

	// API路由
	apiGroup := router.Group("/api")
	{
		apiGroup.POST("/login", c.Login)
	}
}

func (c *AuthController) Login(ctx *gin.Context) {
	var req LoginRequest
	if err := ctx.ShouldBindJSON(&req); err != nil {
		agin.WriteResponse(ctx, agin.ResponseData{
			Code:    http.StatusBadRequest,
			Message: "Invalid request parameters",
		}, err)
		return
	}

	// 验证用户凭据
	_, err := c.userSvc.VerifyUser(req.Username, req.Password)
	if err != nil {
		agin.WriteResponse(ctx, agin.ResponseData{
			Code:    http.StatusUnauthorized,
			Message: "Invalid username or password",
		}, err)
		return
	}

	agin.WriteResponse(ctx, agin.ResponseData{
		Code:    http.StatusOK,
		Message: "Login successful",
		Data:    LoginResponse{Token: "dummy_token"},
	}, nil)
}
